<template>
  <base-modal
    :show.sync="visible"
    width="600px"
    class="base-export-modal base-export-modal-group"
  >
    <template slot="title">
      <h3 v-if="isShowExportTip">
        {{$t('component.baseExport.title')}}
        <el-tooltip placement="top">
          <template slot="content">
            {{$t('component.baseExport.tooltip')}}
            <span class="export-link" @click="toExport">{{$t('component.baseExport.toImport')}}</span>
          </template>
          <i class="iconfont icon-warning-circle-fill task-icon icon-color"></i>
        </el-tooltip>
      </h3>
      <h3 v-else>
        {{$t('component.baseExport.title')}}
      </h3>
    </template>
    <!-- start 分组 -->
    <div>
      <el-checkbox v-model="isCheckedAll" @change="toggle">{{$t('common.base.selectAll')}}</el-checkbox>
      <el-checkbox-group
        v-model="checkedGroupArr"
        @change="handleChangeGroup"
        style="width:100%;"
        class="base-export-field-wrap"
      >
        <template>
          <el-checkbox
            v-for="(col, index) in filterColumns"
            :key="`${col.label}_${index}`"
            :label="col.value"
          >
            {{ col.label }}
          </el-checkbox>
        </template>
      </el-checkbox-group>
    </div>

    <div class="base-export-modal-content" v-if="needchooseBreak">
      <div class="base-export-modal-title">
        {{$t('component.baseExport.exportOption')}}
      </div>
      <el-checkbox v-model="tooltip" class="base-export-field-wrap export-option-checkbox" :title="$t('component.baseExport.exportOptionCheckboxTitle')">{{$t('component.baseExport.exportOptionCheckbox')}}</el-checkbox>
    </div>
    <div
      class="base-export-modal-content"
      v-for="(item, index) in filterColumns"
      :key="`${item.label}_${index}`"
    >
      <div class="base-export-modal-title">
        {{ item.label }}
      </div>

      <el-checkbox-group
        v-model="checkedMap[item.value]"
        @change="handleChange"
        style="width:100%;"
        class="base-export-field-wrap"
      >
        <template>
          <el-checkbox
            v-for="(col, index) in item.columns"
            :key="`${col.field}_${index}`"
            v-if="!col.bool"
            :label="col.exportAlias ? col.exportAlias : col.field"
          >
            {{ col.label }} 
            <div class="tooltip" v-if="item.value === 'taskChecked' && col.formType === 'select' && col.setting.isMulti">{{$t('common.base.multipleRowsData')}}</div>
            <div class="tooltip" v-if="item.value === 'receiptChecked' && col.formType === 'select' && col.setting.isMulti">{{$t('common.base.multipleRowsData')}}</div>
            <div class="tooltip" v-if="item.value === 'receiptChecked' && (col.fieldName === 'spare_name' || col.fieldName === 'service_name')">{{$t('common.base.multipleRowsData')}}</div>
            <div class="tooltip" v-if="item.value === 'systemChecked' && (col.fieldName === 'executorTag' || col.fieldName === 'synergies')">{{$t('common.base.multipleRowsData')}}</div>
            <div class="tooltip" v-if="item.value === `annexChecked${index}` && col.inputType =='multiple'">{{$t('common.base.multipleRowsData')}}</div>
            <div class="tooltip" v-if="item.value === `annexChecked${index}` && col.inputType =='single' && col.formType =='selectMulti'">{{$t('common.base.multipleRowsData')}}</div>
          </el-checkbox>
        </template>
      </el-checkbox-group>
    </div>
    <!-- end 分组 -->

    <div slot="footer" class="export-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" :disabled="pending" @click="exportData(true)">
        {{ pending ? $t('common.base.exporting') : $t('common.base.export') }}
      </el-button>
    </div>

    <div class="base-export-bridge" ref="bridge"></div>
  </base-modal>
</template>

<script>
import { t } from '@src/locales'
import baseExportMixin from '@src/mixins/baseExportMixin';
import { storageGet, storageSet } from '@src/util/storage';
import { string } from 'mathjs';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
let filterColumnsExpandLength = 0;
let filterColumnsExpand = [];
let filterColumnsMap = {};

export default {
  name: 'base-export-group-product',
  mixins: [baseExportMixin],
  props: {
    action: String,
    alert: Function,
    buildParams: Function,
    columns: Array,
    downloadUrl: String,
    group: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: t('component.baseExport.title'),
    },
    method: {
      type: String,
      default: 'get',
    },
    /**
     * 函数必须返回Promise对象
     * 如果验证失败，promise需要返回错误信息，否则返回null
     */
    validate: Function,
    needchooseBreak:{
      type: Boolean | String,
      default: true,
    },
    isShowExportTip:{
      type: Boolean | String,
      default: false,
    },
  },
  data() {
    let checkedMap = {};
    let columns = this.columns;

    columns.forEach((column) => {
      checkedMap[column.value] = [];
    });
    return {
      checkedMap,
      checkedGroupArr: [],
      ids: [],
      fileName: '',
      visible: false,
      pending: false,
      checkedArr: [],
      isCheckedAll: true,
      tooltip: true,
      isDownloadNow: false, // 导出是否是立刻下载模式

      checked: '',
    };
  },
  watch: {
    columns(columns) {
      let checkedMap = {};
      columns.forEach((column) => {
        checkedMap[column.value] = [];
      });
      this.checkedMap = checkedMap;
    },
    tooltip(v) {
      storageSet('tooltipProduct', v)
      // localStorage.setItem('tooltipProduct', v)
    },
  },
  computed: {
    checkedLength() {
      let checkedMap = this.checkedMap;
      let length = 0;

      for (let key in checkedMap) {
        let columns = checkedMap[key];
        length += columns.length;
      }

      return length;
    },
    filterColumns() {
      filterColumnsExpandLength = 0;
      return this.columns.map((item) => {
        let columns = item.columns || [];

        if (Array.isArray(columns) || columns.length < 1) {
          console.warn('Caused: base-export-group filter columns item has no columns');
        }

        item.columns = columns.filter((column) => column.export && column.formType != 'attachment');

        filterColumnsExpandLength += item.columns.length;
        filterColumnsExpand.push(...item.columns);
        filterColumnsMap[item.value] = item.columns;
        return item;
      });
    },
  },
  methods: {
    toExport(){
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityDepartment,
      })
    },
    buildParamsFunc() {
      return typeof this.buildParams == 'function'
        ? this.buildParams(this.checkedMap, this.ids, this.tooltip)
        : { checked: this.checkedArr.join(','), ids: this.ids.join(',') };
    },
    checkedAll(checkedAll = true) {
      let checkedMap = this.checkedMap;

      this.checkedGroupArr = [];
      for (let key in checkedMap) {
        let item = checkedMap[key];
        let columns = filterColumnsMap[key];

        let checkedArr = [];

        if (checkedAll) {
          checkedArr = columns.map((item) =>
            item.exportAlias ? item.exportAlias : item.field
          );

          this.checkedGroupArr.push(key);
        }

        this.$set(this.checkedMap, key, checkedArr);
      }
    },
    handleChange() {
      this.isCheckedAll = this.checkedLength == filterColumnsExpandLength;
      storageSet('checkedMapProduct', JSON.stringify(this.checkedMap))
      storageSet('checkedGroupArrProduct', JSON.stringify(this.checkedGroupArr))
      storageSet('isCheckedAllProduct', this.isCheckedAll)

      // localStorage.setItem('checkedMapProduct', JSON.stringify(this.checkedMap))
      // localStorage.setItem('checkedGroupArrProduct', JSON.stringify(this.checkedGroupArr))
      // localStorage.setItem('isCheckedAllProduct', this.isCheckedAll)
    },
    handleChangeGroup(value) {
      let checkedMap = this.checkedMap;

      this.checkedGroupArr = [];

      for (let key in checkedMap) {
        let checkedArr = [];

        if (value.indexOf(key) > -1) {
          let columns = filterColumnsMap[key] || [];

          checkedArr = columns.map((item) =>
            item.exportAlias ? item.exportAlias : item.field
          );

          this.checkedGroupArr.push(key);
        }

        this.$set(this.checkedMap, key, checkedArr);
      }

      this.handleChange();
    },
    isCheckedEmpty() {
      return filterColumnsExpandLength == 0;
    },
    open(ids = [], fileName = `${t('common.base.exportData')}.xlsx`, isDownloadNow = false) {
      this.pending = false;
      this.ids = ids;
      this.fileName = fileName;

      this.isCheckedAll = true;
      this.checkedAll();

      if (storageGet('checkedMapProduct')) {
        // this.checkedMap = JSON.parse(storageGet('checkedMapProduct'))
        this.checkedMap = Object.assign(this.checkedMap, JSON.parse(storageGet('checkedMapProduct')));
      }
      if (storageGet('checkedGroupArrProduct')) {
        this.checkedGroupArr = JSON.parse(storageGet('checkedGroupArrProduct'))
      }
      if (storageGet('isCheckedAllProduct')) {
        this.isCheckedAll = storageGet('isCheckedAllProduct') === 'true'
      }
      if (storageGet('tooltipProduct')) {
        this.tooltip = storageGet('tooltipProduct') === 'true'
      }

      this.isDownloadNow = isDownloadNow;

      this.visible = true;
    },
    toggle(value) {
      this.checkedAll(value);
      storageSet('checkedMapProduct', JSON.stringify(this.checkedMap))
      storageSet('checkedGroupArrProduct', JSON.stringify(this.checkedGroupArr))
      storageSet('isCheckedAllProduct', this.isCheckedAll)
    },
  },
};
</script>

<style lang="scss">
@import "./../BaseExport/BaseExport.scss";

.base-export-modal-group {
  .base-export-modal-content {
    margin-top: 10px;
  }

  .base-export-modal-title {
    font-weight: 500;
    font-size: 15px;
    line-height: 30px;
    height: 30px;
  }
  .tooltip {
    background-color: #4472C4;
    margin-left: 3px;
    margin-bottom: 0px;
    padding: 2px 6px;
    color: white;
    display: inline-block;
  }
}
</style>
<style lang="scss" scoped>
.export-link {
  color: $color-primary-light-6;
  cursor: pointer;
  text-decoration: underline;
}
.export-option-checkbox {
  ::v-deep .el-checkbox__label {
    flex: 1;
    white-space: pre-wrap;
  }
}
</style>
